package com.zhuxiang.test2;

/**
 * 编程获取两个指定字符串中的最大相同子串。
 *
 *  如： s1="asdafghjka", s2="aaasdfg" 他们的最大子串为"asd"
 */
public class Demo2 {

    public static void main(String[] args) {
        //定义两个字符串
        String s1 = "asdafghjka";
        String s2 = "aaasdfg";
        StringBuilder sb = new StringBuilder();
        //两个字符串的长度比大小
        String max = "";
        String min = "";
        max = (s1.length() > s2.length()) ? s1:s2;
        min = (s1.length() < s2.length()) ? s1:s2;
        for (int i = 0; i < min.length(); i++) {
            for (int j = 0,k=min.length()-i; k <=min.length(); j++,k++) {
                String str = min.substring(j,k);
                if (max.contains(str)){
                    sb.append(str+" ");
                }
            }
        }
        //查找最长字符串
        String[] arr = sb.toString().split(" ");
        int index = 0;
        for (int i = 1; i < arr.length; i++) {
           if (arr[i].length() > arr[index].length()){
                    index=i;
           }
        }
        System.out.println("最大相同字符串是："+arr[index]);
    }
}
